// 页面简单增删改查的逻辑复用
import { ref, nextTick, createVNode } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import debounce from 'lodash/debounce';
import qs from 'qs';
import { useUser } from '@/pinia-store/user';

// 列表页面逻辑复用
export const useRequest = () => {
  const dataFormModalShowHide = ref(false)
  const addOrUpdataRef = ref()
  // 请求配置
  const requestObj = ref({
    listApi: null, // 列表查询
    createApi: null, // 新增
    updataApi: null, // 修改
    deleteApi: null, // 删除
    exportURL: '', // 导出
    isPage: false, // 是否是分页接口
    isTree: false, // 是否是树形结构
    deleteMany: false, // 是否多选删除
    dataLoading: false, // 列表数据loading
    emptyText: '暂无数据', // 数据为空展示
    query: {}, // 查询参数
    dataList: [], // 数据源
  })
  // 分页配置
  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: total => `共 ${total} 条`,
    position: ['bottomCenter']
  })
  // 表格行选择配置
  const rowSelection = ref({
    checkStrictly: false, // checkable 状态下节点选择完全受控（父子数据选中状态不再关联）
    columnTitle: '', // 自定义列表选择框标题
    columnWidth: '', // 自定义列表选择框宽度
    fixed: false, // 把选择框列固定在左边
    hideSelectAll: false, //隐藏全选勾选框与自定义选择项
    preserveSelectedRowKeys: false, // 当数据被删除时仍然保留选项的 key
    hideDefaultSelections: false, // 去掉『全选』『反选』两个默认选项
    selectedRowKeys: [], // 指定选中项的 key 数组，需要和 onChange 进行配合
    type: 'checkbox', // 多选/单选，checkbox or radio
    onChange: (selectedRowKeys) => {
      console.log(selectedRowKeys);
      rowSelection.value.selectedRowKeys = [...new Set([...rowSelection.value.selectedRowKeys, ...selectedRowKeys])]
    },
    onSelect: (record, selected) =>{
      let index = rowSelection.value.selectedRowKeys.indexOf(record.id)
      if (!selected) {
        rowSelection.value.selectedRowKeys.splice(index, 1)
      }
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      if (!selected) {
        changeRows.forEach(item => {
          let index = rowSelection.value.selectedRowKeys.indexOf(item.id)
          if (index > -1) {
            rowSelection.value.selectedRowKeys.splice(index, 1)
          }
        })
      }
    }
  })

  // 初始化请求参数
  const requestInit = (load) => {
    requestObj.value = {
      ...requestObj.value,
      ...load
    }
    pagination.value.current = load.isPage ? load.query.page : 1
    pagination.value.pageSize = load.isPage ? load.query.limit : 20
    getDataList()
  }
  // 获取列表数据
  // eslint-disable-next-line no-unused-vars
  const getDataList = debounce((paginationObj, filters, sorter) => {
    requestObj.value.dataLoading = true
    if (paginationObj) {
      requestObj.value.query.page = paginationObj.current
      requestObj.value.query.limit = paginationObj.pageSize
      pagination.value.pageSize = paginationObj.pageSize
      pagination.value.current = paginationObj.current
    } else {
      requestObj.value.query.page = 1
      pagination.value.current = 1
    }
    requestObj.value.listApi(requestObj.value.query).then(({data:res}) => {
      if (requestObj.value.isPage) {
        pagination.value.total = res.data.total
        requestObj.value.dataList = res.data.list
      } else {
        if (requestObj.value.isTree) {
          const fn = (list) => {
            list.forEach(item => {
              item.children = item.children && item.children.length ? item.children : null
              if (item.children) {
                fn(item.children)
              }
            })
          }
          fn(res.data)
        }
        requestObj.value.dataList = res.data
      }
    }).finally(() => {
      requestObj.value.dataLoading = false
    })
  }, 200) 
  // 打开新增修改弹窗
  const addOrUpdata = (id) => {
    dataFormModalShowHide.value = true
    nextTick(() => {
      addOrUpdataRef.value.init(id)
    })
  }

  // 公用提醒
  const commonRemind = (callback, modalInfo={title: '温馨提示', content: '确定删除所选数据吗？'}) => {
    Modal.confirm({
      title: modalInfo.title,
      okText: '确认',
      cancelText: '取消',
      icon: createVNode(ExclamationCircleOutlined),
      content: modalInfo.content,
      onOk() {
        callback()
      }
    })
  }

  // 删除
  const deleteData = (id) => {
    if (requestObj.value.deleteMany) {
      let ids = id ? [id] : rowSelection.value.selectedRowKeys
      if (!ids.length) {
        return message.warning('请至少选择一条数据')
      }
      if (!id) {
        Modal.confirm({
          title: '温馨提示',
          okText: '确认',
          cancelText: '取消',
          icon: createVNode(ExclamationCircleOutlined),
          content: '确定删除所选数据吗？',
          onOk() {
            return requestObj.value.deleteApi(ids).then(() => {
              message.success('操作成功！')
              rowSelection.value.selectedRowKeys = []
              getDataList()
            })
          }
        })
      } else {
        requestObj.value.deleteApi(ids).then(() => {
          message.success('操作成功！')
          let index = rowSelection.value.selectedRowKeys.indexOf(id)
          if (index !== -1) {
            rowSelection.value.selectedRowKeys.splice(index, 1)
          }
          getDataList()
        })
      }
    } else {
      requestObj.value.deleteApi(id).then(() => {
        message.success('操作成功！')
        let index = rowSelection.value.selectedRowKeys.indexOf(id)
        if (index !== -1) {
          rowSelection.value.selectedRowKeys.splice(index, 1)
        }
        getDataList()
      })
    }

  }
  // 导出数据
  const exportExcal = debounce(() => {
    let baseUrl = import.meta.env.VITE_USER_NODE_ENV === "development" ? import.meta.env.VITE_APP_API : import.meta.env.VITE_APP_BASE_API
    window.location.href = `${baseUrl}${requestObj.value.exportURL}?${qs.stringify({
      ...requestObj.value.query,
      token: useUser().token
    })}`;
  }, 200)
  // 弹窗回调
  const modalClose = (isRefresh) => {
    dataFormModalShowHide.value = false
    if (isRefresh) {
      getDataList()
    }
  }

  return {
    dataFormModalShowHide,
    addOrUpdataRef,
    requestObj,
    pagination,
    rowSelection,
    requestInit,
    getDataList,
    addOrUpdata,
    deleteData,
    commonRemind,
    exportExcal,
    modalClose
  }
}

// 表单页面逻辑复用
export const useFormOperate = () => {
  const dataFormRef = ref()
  const modalOpen = ref(false)
  const detailLoading = ref(false)
  const confirmLoading = ref(false)
  const dataForm = ref({})
  const requestObj = ref({
    createApi: null,
    updataApi: null,
    getInfoApi: null,
    submitCallback: null
  })
  
  // 初始化
  const init = (id) => {
    modalOpen.value = true
    dataForm.value.id = id
    if (id) {
      getInfo()
    }
  }
  // 获取表单详情
  const getInfo = () => {
    detailLoading.value = true
    requestObj.value.getInfoApi(dataForm.value.id).then(({data:res}) => {
      // 不给后端带过去多余的字段，想要的话再dataForm里面添加
      for (let key in dataForm.value) {
        dataForm.value[key] =(res.data[key] !== undefined && res.data[key] !== null) ? res.data[key] : dataForm.value[key]
      }
    }).finally(() => {
      detailLoading.value = false
    })
  }
  const submit = () => {
    dataFormRef.value.validate().then(() => {
      confirmLoading.value = true
      const submitApi = dataForm.value.id ? requestObj.value.updataApi : requestObj.value.createApi
      submitApi(dataForm.value).then(() => {
        message.success('操作成功！')
        modalOpen.value = false
        requestObj.value.submitCallback('modalClose', true)
      }).finally(() => {
        confirmLoading.value = false
      })
    })
  }

  return {
    dataFormRef,
    modalOpen,
    detailLoading,
    confirmLoading,
    dataForm,
    requestObj,
    init,
    getInfo,
    submit
  }
}